import * as serviceApi from '@/services/user';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'user',

  state: {
    list: [],
    currentUser: {},
  },

  effects: {
    *get(_, { call, put }) {
      const response = yield call(serviceApi.get);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *getCurrent(_, { call, put }) {
      const savedId = localStorage.getItem("zytc_logon_user");
      if (savedId) {
        const response = yield call(serviceApi.getCurrent, savedId);
        yield put({
          type: 'saveCurrentUser',
          payload: response
        })
        return response;
      } else {
        yield put(
          routerRedux.push({
            pathname: '/user/login',
          })
        );
      }
    },
    *createOrUpdate({ payload, callback }, { call, put }) {
      const isEdit = payload.id && payload.id > 0;
      if (!isEdit) {
        payload = {
          ...payload,
          password: '888888'  // 创建用户时，传递明文密码.
        }
      }
      const res = yield call(isEdit ? serviceApi.updateAccountInfo : serviceApi.createAccount, payload);
      if (callback)
        callback(res);

    },

  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
  },
};
